#include "db.h"

#include <QSqlError>
#include <QSqlQuery>

#include <QtWidgets/QMessageBox>

DB::DB(QObject *parent) :
    QObject(parent)
{
}

QString DB::hostName() {
    return m_hostName;
}

void DB::setHostName(QString hostName) {
    this->m_hostName = hostName;
}

QString DB::databaseName() {
    return m_databaseName;
}

void DB::setDatabaseName(QString databaseName) {
    this->m_databaseName = databaseName;
}

QString DB::userName() {
    return m_userName;
}

void DB::setUserName(QString userName) {
    this->m_userName = userName;
}

QString DB::password() {
    return m_password;
}

void DB::setPassword(QString password) {
    this->m_password = password;
}

bool DB::connect() {
    return doConnection();
}

void DB::closeConnection() {
    db.close();
}

bool DB::connectSlot() {
    return doConnection();
}

bool DB::doConnection() {
    bool result = false;
    QSqlDatabase database;

    if(db.isOpen()) {
        result = true;
    } else {
        QString dbName = db.connectionName();

        db = database;

        QSqlDatabase::removeDatabase(dbName);
        database = QSqlDatabase::addDatabase("QIBASE");
        database.setHostName(m_hostName);
        database.setDatabaseName(m_databaseName);
        database.setUserName(m_userName);
        database.setPassword(m_password);

        result = database.open();
        db = database;
    }

    if(!result) {
        qDebug(database.lastError().text().toUtf8());
    }

    return result;
}
